#!/usr/bin/env python
# -*- coding:utf-8 -*-

import datetime
import math
import json

from sqlalchemy import or_

from app import db
from models.repairInfoModel import RepairInfo
from utils import commons
from utils.response_code import RET, error_map_EN
from utils.loggings import loggings


class RepairInfoController(RepairInfo):

    # add
    @classmethod
    def add(cls, **kwargs):
        from utils.generate_id import GenerateID
        repairID = GenerateID.create_random_id()
        
        try:
            model = RepairInfo(
                repairID=repairID,
                repairPlace=kwargs.get('repairPlace'),
                repairType=kwargs.get('repairType'),
                repairDetail=kwargs.get('repairDetail'),
                contactName=kwargs.get('contactName'),
                contactPhone=kwargs.get('contactPhone'),
                status=kwargs.get('status'),
                userID=kwargs.get('userID'),
                workID=kwargs.get('workID'),
                updateTime=kwargs.get('updateTime'),
                finishTime=kwargs.get('finishTime'),
                createTime=kwargs.get('createTime'),
                
            )
            db.session.add(model)
            db.session.commit()
            results = {
                'add_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'repairID': model.repairID,
                
            }
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # get
    @classmethod
    def get(cls, **kwargs):
        try:
            filter_list = [cls.isDelete == 0]
            if kwargs.get('repairID'):
                filter_list.append(cls.repairID == kwargs['repairID'])
            else:
                if kwargs.get('repairPlace'):
                    filter_list.append(cls.repairPlace == kwargs.get('repairPlace'))
                if kwargs.get('repairType'):
                    filter_list.append(cls.repairType == kwargs.get('repairType'))
                if kwargs.get('repairDetail'):
                    filter_list.append(cls.repairDetail == kwargs.get('repairDetail'))
                if kwargs.get('contactName'):
                    filter_list.append(cls.contactName == kwargs.get('contactName'))
                if kwargs.get('contactPhone'):
                    filter_list.append(cls.contactPhone == kwargs.get('contactPhone'))
                if kwargs.get('status') is not None:
                    filter_list.append(cls.status == kwargs.get('status'))
                if kwargs.get('userID') is not None:
                    filter_list.append(cls.userID == kwargs.get('userID'))
                if kwargs.get('workID') is not None:
                    filter_list.append(cls.workID == kwargs.get('workID'))
                if kwargs.get('updateTime'):
                    filter_list.append(cls.updateTime == kwargs.get('updateTime'))
                if kwargs.get('finishTime'):
                    filter_list.append(cls.finishTime == kwargs.get('finishTime'))
                if kwargs.get('createTime'):
                    filter_list.append(cls.createTime == kwargs.get('createTime'))
                

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))
            
            repairInfo_info = db.session.query(cls).filter(*filter_list)
            
            count = repairInfo_info.count()
            pages = math.ceil(count / size)
            repairInfo_info = repairInfo_info.limit(size).offset((page - 1) * size).all()
   
            results = commons.query_to_dict(repairInfo_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages, 'data': results}
            
        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # delete
    @classmethod
    def delete(cls, **kwargs):
        try:
            filter_list = [cls.isDelete == 0]
            if kwargs.get('repairID'):
                primary_key_list = []
                for primary_key in str(kwargs.get('repairID')).replace(' ', '').split(','):
                    primary_key_list.append(cls.repairID == primary_key)
                filter_list.append(or_(*primary_key_list))
                
            else:
                if kwargs.get('repairPlace'):
                    filter_list.append(cls.repairPlace == kwargs.get('repairPlace'))
                if kwargs.get('repairType'):
                    filter_list.append(cls.repairType == kwargs.get('repairType'))
                if kwargs.get('repairDetail'):
                    filter_list.append(cls.repairDetail == kwargs.get('repairDetail'))
                if kwargs.get('contactName'):
                    filter_list.append(cls.contactName == kwargs.get('contactName'))
                if kwargs.get('contactPhone'):
                    filter_list.append(cls.contactPhone == kwargs.get('contactPhone'))
                if kwargs.get('status') is not None:
                    filter_list.append(cls.status == kwargs.get('status'))
                if kwargs.get('userID') is not None:
                    filter_list.append(cls.userID == kwargs.get('userID'))
                if kwargs.get('workID') is not None:
                    filter_list.append(cls.workID == kwargs.get('workID'))
                if kwargs.get('updateTime'):
                    filter_list.append(cls.updateTime == kwargs.get('updateTime'))
                if kwargs.get('finishTime'):
                    filter_list.append(cls.finishTime == kwargs.get('finishTime'))
                if kwargs.get('createTime'):
                    filter_list.append(cls.createTime == kwargs.get('createTime'))
                
            res = db.session.query(cls).filter(*filter_list).with_for_update()

            results = {
                'delete_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'repairID': []
            }
            for query_model in res.all():
                results['repairID'].append(query_model.repairID)

            res.update({'isDelete': 1})
            db.session.commit()

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()
    
    # update
    @classmethod
    def update(cls, **kwargs):
        try:
            
            filter_list = [cls.isDelete == 0]
            filter_list.append(cls.repairID == kwargs.get('repairID'))
            
            res = db.session.query(cls).filter(*filter_list).with_for_update()

            results = {
                'update_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'repairID': res.first().repairID,
                
            }
            
            res.update(kwargs)
            db.session.commit()

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # batch add
    @classmethod
    def add_list(cls, **kwargs):
        param_list = json.loads(kwargs.get('RepairInfoList'))
        model_list = []
        for param_dict in param_list:
            from utils.generate_id import GenerateID
            repairID = GenerateID.create_random_id()
            
            model = RepairInfo(
                repairID=repairID,
                repairPlace=param_dict.get('repairPlace'),
                repairType=param_dict.get('repairType'),
                repairDetail=param_dict.get('repairDetail'),
                contactName=param_dict.get('contactName'),
                contactPhone=param_dict.get('contactPhone'),
                status=param_dict.get('status'),
                userID=param_dict.get('userID'),
                workID=param_dict.get('workID'),
                updateTime=param_dict.get('updateTime'),
                finishTime=param_dict.get('finishTime'),
                createTime=param_dict.get('createTime'),
                
            )
            model_list.append(model)
        
        try:
            db.session.add_all(model_list)
            db.session.commit()
            results = {
                'added_records': [],
                'add_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            for model in model_list:
                added_record = {}
                added_record['repairID'] = model.repairID
                
                results['added_records'].append(added_record)
            
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()
